package com.seewo.dubbo.debugger.core;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import com.seewo.dubbo.debugger.api.ApiDebuggerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chenliangliang
 * @date 2018/7/26
 */
@Slf4j
class ApiServiceRegister {


    void register(ApplicationContext ctx) {
        ApplicationConfig applicationConfig = ctx.getBean(ApplicationConfig.class);

        String[] registryBeanNames = ctx.getBeanNamesForType(RegistryConfig.class);
        List<RegistryConfig> registryConfigs = new ArrayList<>();
        for (String registryBeanName : registryBeanNames) {
            RegistryConfig registryConfigBean = (RegistryConfig) ctx.getBean(registryBeanName);
            registryConfigs.add(registryConfigBean);
        }

        String[] protocolBeanNames = ctx.getBeanNamesForType(ProtocolConfig.class);
        List<ProtocolConfig> protocolConfigs = new ArrayList<>();
        for (String protocolBeanName : protocolBeanNames) {
            ProtocolConfig protocolConfigBean = (ProtocolConfig) ctx.getBean(protocolBeanName);
            protocolConfigs.add(protocolConfigBean);
        }


        ServiceConfig<ApiDebuggerService> serviceConfig = new ServiceConfig<>();
        serviceConfig.setApplication(applicationConfig);
        serviceConfig.setRegistries(registryConfigs);
        serviceConfig.setProtocols(protocolConfigs);
        serviceConfig.setInterface(ApiDebuggerService.class);
        serviceConfig.setRef(new ApiDebuggerServiceImpl());
        serviceConfig.setRetries(3);
        serviceConfig.setVersion("1.0.0");

        serviceConfig.export();
        log.info("注册Dubbo服务成功");
    }

}
